package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public ResultInfo login(String username, String password) {
        //1.根据用户名从数据库查询，查询不到直接返回错误信息
        Employee employee = employeeMapper.findByUsername(username);
        if (employee == null) {
            return ResultInfo.error("当前用户名不存在");
        }
        //2.判断用户状态，如果不是1直接返回错误信息
        if (employee.getStatus() != Employee.STATUS_ENABLE) {
            return ResultInfo.error("当前用户未激活");
        }
        //3.将前端传入的密码加密，然后进行比对，如果比对失败的话，直接返回错误信息
        String passwordMd5 = SecureUtil.md5(password);
        String passwordFromDb = employee.getPassword();
        if (!StringUtils.equals(passwordMd5, passwordFromDb)) {
            return ResultInfo.error("密码错误");
        }
        //4.返回成功信息
        return ResultInfo.success(employee);
    }

    @Override
    public List<Employee> findByName(String name) {
        List<Employee> employeeList = employeeMapper.findByName(name);
        return employeeList;
    }

    @Override
    public void save(Employee employee) {
        //1.将employee的其余属性赋值
        long id = IdUtil.getSnowflake(1, 1).nextId();
        employee.setId(id);
        //密码默认为123456,并进行加密
        String md5 = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(md5);

        employee.setStatus(Employee.STATUS_ENABLE);
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
        //更新 创建用户，临时写死
//        employee.setCreateUser(1l);
//        employee.setUpdateUser(1l);
        //2.保存
        employeeMapper.save(employee);

    }

    @Override
    public ResultInfo findById(Long id) {
        Employee employee = employeeMapper.findById(id);
        if (employee != null) {
            return ResultInfo.success(employee);
        }
        return ResultInfo.error("网络错误，请联系管理员");

    }

    @Override
    public void update(Employee employee) {
//        employee.setUpdateTime(new Date());
//        employee.setUpdateUser(1l);
        employeeMapper.update(employee);
    }
}
